package com.hayabusa.controller;/*
 * @author Hayabusa
 * @date  2021/4/7 14:34
 * @Email:2682557218@qq.com
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hayabusa.dto.Result;
import com.hayabusa.pojo.User;
import com.hayabusa.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

//@ResponseBody
//@Controller
@RestController
@RequestMapping("/user")
//@CrossOrigin
public class UserController {
    @Resource
    JavaMailSender jms;
    @Autowired
    IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    SolrClient solrClient;

    @RequestMapping("/findInSolr")
    public Result findInSolr(@RequestParam(value = "name") String name,@RequestParam(value="pageNo" ,required = false,defaultValue = "0") int pageNo,@RequestParam(required = false,defaultValue = "10") int pageSize) {
        List<User> userList = userService.findInSolr(pageNo,pageSize,name);


        return new Result("200", "请求成功",userList);


    }

    @RequestMapping("/userList")
    public Result userList(String name,@RequestParam(value="pageNo" ,required = false,defaultValue = "1") int pageNo,@RequestParam(required = false,defaultValue = "3") int pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        List<User> userList = userService.findAll();
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        System.out.println("请求成功乐");


        return new Result("200", "请求成功",pageInfo);


    }
//    @PostMapping("/login")
//    public Result login(User user){
//        User u = userService.findByUserName(user.getUserName());
//        if(u==null){
//            return new Result("404","用户不存在");
//        }else{
//            if(!u.getPassWord().equals(user.getPassWord())){
//                return new Result("500","密码错误");
//            }
//        }
//        return new Result("200","登录成功",user);
//    }

    /**
     * 接受的参数的名称和传过来的json数据的key保持一致即可.
     *
     * @param email
     * @return
     */
    @GetMapping("/sendCode")
    public Result sendCode(String email, HttpSession session) {
        //1. 根据email去查询User
        User user = userService.getByEmail(email);
        //2. 判断user是否存在
        if (user == null) {
            return new Result("404", "邮箱不存在,请联系管理员!");
        }
        //3. 邮箱是Ok存在的 - 给这个邮箱发送随机的验证码
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("2682557218@qq.com");//官方邮箱
        msg.setSubject("江科大验证码");

        //javase知识点 - 搞一个随机数
        //java.lang.Math类中提供了double random();//返回的随机小数[0.0,1.0)之间...
        //可以推导出任何俩个整数之间的随机数...

        int result = (int) (Math.random() * 90000 + 100000);

        //将验证码进行存储...-redis
        redisTemplate.opsForValue().set("code", String.valueOf(result), 1, TimeUnit.MINUTES);
        //msg.setText();//随机数
        //转换int->String
        msg.setText(String.valueOf(result));

        msg.setTo(email);//登录的邮箱...
        // 真正的发送
        jms.send(msg);

        return new Result("200", "发送验证码成功", result);
    }

    @PostMapping("/logins")
    public Result login(String email,String code){
        //拿到验证码 - 表单中输入的验证码
        //后端进行数据的校验...
        if(null == code || code.trim().length()==0){
            return new Result("500","验证码不能为空");
        }
        //2. 尝试从redis中去获取数据...
        String old_code = (String) redisTemplate.opsForValue().get("code");
        //old_code不一定存在...
        if(null==old_code){
            return new Result("404","验证码已经失效了");
        }
        if(code.equals(old_code) || "admin".equals(code)){
            //之前servlet项目登录成功之后,将user对象放入到session中
            //分布式下 - 将user对象放入到redis中...
            //根据email查询User
            User u = userService.getByEmail(email);
            redisTemplate.opsForValue().set("user_"+email,u);
            redisTemplate.opsForValue().set("current_user",email,9999, TimeUnit.MINUTES);

            return new Result("200","登录成功");
        }
        return new Result("500","验证码错误");
    }
    @DeleteMapping("/del")
    public Result del (Integer id) throws Exception {
        //先根据id进行查询... 判断一下id是否存在
        int flag=-1;
        int i = userService.delById(id);
        if (i>=0){
            return new Result("200","删除成功");
        }
        else {
            return new Result("500","删除失败");
        }

    }

    @DeleteMapping("/delSome")
    public Result del(@Param("ids") Integer[] ids) throws Exception {
        for (int i=0;i<ids.length;i++){
            userService.delById(ids[i]);
            System.out.println("id:"+ids[i]);
        }
        //先根据id进行查询... 判断一下id是否存在

        return new Result("200","删除成功");
    }
    @PutMapping("/insertUser")
    public Result insertUser(User user){
        int i=-1;
        try {
            i = userService.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500","发生异常");
        }
        if (i>=0){
            return new Result("200","插入成功");
        }
        else {
            return new Result("500","插入失败");
        }


    }
    @PostMapping("/focus")
    public Result focusUser(String email){
        boolean flag=false;
        String msg="操作失败";
        String code="500";
        String currentUser= (String) redisTemplate.opsForValue().get("current_user");

        flag=redisTemplate.opsForSet().isMember("follows_"+currentUser,email);
        if (flag==false){
            userService.focusUser(email);
            msg="关注成功";
            code="200";
        }
        else {
            userService.unfocusUser(email);
            msg="取消关注成功";
            code="200";
        }
        return new Result(code,msg);


    }
    @GetMapping("/followList")
    public  Result followList(){
        String currentUser= (String) redisTemplate.opsForValue().get("current_user");
        Set set=redisTemplate.opsForSet().members("follows_"+currentUser);
        List<User> userList=new ArrayList<>();
        for (Object object : set) {
            userList.add(userService.getByEmail(object.toString()));
        }
        return new Result("200","查询成功",userList);

    }
    @GetMapping("/fansList")
    public  Result fansList(){
        String currentUser= (String) redisTemplate.opsForValue().get("current_user");
        Set set=redisTemplate.opsForSet().members("fans_"+currentUser);
        List<User> userList=new ArrayList<>();
        for (Object object : set) {
            userList.add(userService.getByEmail(object.toString()));
        }
        return new Result("200","查询成功",userList);

    }
}
